var express = require('express');
var router = express.Router();
const QuestModel = require("../db/questModel");
const AnswerModel = require("../db/answerModel");

router.get('/', async (req, res) => {
    const urlStr = req.url
    const f = {"username":req.user.username}
    const param = urlStr.split('?')
    if(param.length === 2&&param[1] !== ""){
        const filter = param[1]
        const ft = filter.split('&')
        const filed = ft[0].split('=')
        if(filed[0] === "name")
            f["title"] = {$regex:filed[1]}
        if(filed[0] === "status")
            f["status"] = parseInt(filed[1])
        if(ft.length === 2){
            const filed = ft[1].split('=')
            if(filed[0] === "name")
                f["title"] = {$regex:filed[1]}
            if(filed[0] === "status")
                f["status"] = parseInt(filed[1])
        }
    }

    await QuestModel.find(f,
        {
            "id":1,
            "status":1,
            "endTime":1,
        },
        async function (error,quest) {
            for (i = 0; i < quest.length; i++)
                if (quest[i]._doc["endTime"] !== undefined && quest[i]._doc["endTime"] !== null) {
                    var now = Date.now()
                    if (now > quest[i]._doc["endTime"]) {
                        await QuestModel.updateOne(
                            {"id": quest[i]._doc["id"]},
                            {$set: {"status": 3}}, function (error, data) {
                            })
                    }
                }
        })

    await QuestModel.find(f,
        {
            "_id":0,
            "title":1,
            "id":1,
            "openCode":1,
            "description":1,
            "status":1,
            "lastEditedTime":1,
            "endTime":1,
            "releaseTime":1,
        },
        async function (error,quest){
            for(p = 0;p<quest.length;p++) {
                quest[p]._doc["answerCount"] = await AnswerModel.find({"questId":quest[p].id}).count()
            }
            if(error) {
                res.send([])
            }
            else{
                res.send(quest)
            }
        }
    )
})

module.exports = router;